#ifndef XML_H
#define XML_H
#include"tinyxml.h"
#include"tinystr.h"
#include<iostream>
#include<string>

using namespace std;

void CreatUser(TiXmlElement* newuser, string username)
{
        newuser->SetValue(username.c_str());
        TiXmlElement* firstElement = new TiXmlElement("Node Id Record");
        newuser->LinkEndChild(firstElement);
        firstElement->SetAttribute("Node Id Record",0);

        TiXmlElement* subjects = new TiXmlElement("Subjects");
        newuser->LinkEndChild(subjects);
}

int GetNodeId(TiXmlElement* user)
{
        int NodeIdRecord = 0;
        TiXmlElement* firstElement = NULL;
        firstElement = user->FirstChildElement();
        if(firstElement == NULL)
                cout<<"Error!"<<endl;
        TiXmlAttribute* attr = firstElement->FirstAttribute();
        NodeIdRecord = attr->IntValue();
        return NodeIdRecord;
}

void CreatNode(TiXmlElement* user, TiXmlElement* nodes, TiXmlElement* newnode)//creat the node under a certain user and nodes
{
        newnode->SetValue("Node");
        nodes->LinkEndChild(newnode);

        TiXmlElement* id = new TiXmlElement("NodeId");
        newnode->LinkEndChild(id);
        int newNodeId = 0;
        newNodeId = GetNodeId(user);
        newNodeId++;
        newnode->SetAttribute("Node Id",newNodeId);

        //change the node id record
        TiXmlElement* firstElement = user->FirstChildElement();
        firstElement->SetAttribute("Node Id Record",newNodeId);

        TiXmlText* text = new TiXmlText("Node Text");
        newnode->LinkEndChild(text);
}

void SetText(TiXmlElement* user, TiXmlElement* nodes, TiXmlElement* node,string newtext)
{
        TiXmlNode* textNode = node->IterateChildren("Node Text",node->FirstChild());
        TiXmlText* text = textNode->ToText();
        text->SetValue(newtext.c_str());
}

void AddAdj(TiXmlElement* user, TiXmlElement* nodes, TiXmlElement* node,int adjId)
{
        TiXmlElement* adjNode = new TiXmlElement("Adj Node");
        node->LinkEndChild(adjNode);
        adjNode->SetAttribute("Adj Node",adjId);
}

void DeleteNode(TiXmlElement* nodes, TiXmlElement* node)
{
        nodes->RemoveChild(node);
}

void DeleteAdjNode(TiXmlElement* node,int adjid)
{
        TiXmlNode* adjNode = NULL;
        TiXmlElement* adj = NULL;
        while(node->IterateChildren("Adj Node",node->FirstChild()))
        {
                adjNode = node->IterateChildren("Adj Node",node->FirstChild());
                adj = adjNode->ToElement();
                TiXmlAttribute* attr = adj->FirstAttribute();
                if(adjid = attr->IntValue())
                {
                        node->RemoveChild(adjNode);
                        break;
                }
        }
}

#endif // XML_H
